home *** CD-ROM | disk | FTP | other *** search
- Path: news.mira.net.au!news
- From: davidw@werple.net.au (David White)
- Newsgroups: comp.lang.c++
- Subject: Re: Creating a pointer to a function "void (*ptrFunction)()" inside a class
- Date: 5 Jan 1996 21:39:03 +1100
- Organization: Werple Internet, Melbourne
- Message-ID: <4civ47$hg6@werple.net.au>
- References: <30ECA10F.3D99@ifu.net>
- NNTP-Posting-Host: werple.mira.net.au
-
- Jason Gresh <gresh@ifu.net> writes:
-
- >Hi,
-
- > I am trying to create a base class that has a function that the
- >derived class needs to create. In order to do this, I want to create a
- >pointer to a function in the base class that the derived class can then
- >define. This is not a case where an override will work because the
- >number and names of the derived functions is not known. Hopefully this
- >code sample will make this clearer:
-
- >class BaseClass
- >{
- > int (*ptrFunction)();
- >}
-
- >class DerivedClass : BaseClass
- >{
- > DerivedClass::DerivedClass();
- > int myFunction(int, int);
- >}
-
- >DerivedClass::DerivedClass()
- >{
- > ptrFunction = myFunction;
- >}
-
- >DerivedClass::myFunction(int, int)
- >{
- >// code ....
- >}
-
- >If I don't make myFunction part of the derived class (global),
- >everything works fine. As soon as I include it in the class, I cannot
- >assign a pointer to it. I am aware that pointers to functions inside
- >the class include the class name in some way ( this is not an issue for
- >global functions). What is the casting (or other) mechanism to make
- >this work?
-
-
- Non-static member functions are fundamentally different from global
- functions; they receive an implicit parameter (the 'this' pointer),
- through which they can access the data of the object instance for which
- they are called. Consequently, a pointer to such a function is
- incompatible with a global function pointer. Use the following syntax
- instead:
-
- class BaseClass
- {
- protected:
- // A typedef simplifies things somewhat.
- // Also, the correct function parameters (int, int) are required
- typedef int (BaseClass::*FPTR)(int, int);
- FPTR ptrFunction;
- };
-
- class DerivedClass : BaseClass
- {
- public:
- DerivedClass()
- { ptrFunction = (FPTR)&DerivedClass::myFunction;
- }
- int myFunction(int, int);
- }
-
- The (FPTR) cast is required because 'myFunction' is not a member of
- BaseClass. Here is an example of calling the function:
-
- void BaseClass::f()
- { int n = (this->*ptrFunction)(1, 2);
- }
-
- David White
- davidw@werple.mira.net.au
-
-